<?php


/**
 * Cleans the page param and leaves it as an integer
 * 
 * Only integers allowed
 */
function setPage() {

    if (isset($_GET["page"])) {
        $_SESSION["page"] = intval($_GET["page"]);
    } else {
        $_SESSION["page"] = 1;
    }
}


/**
 * Stores the selected meta value into $_SESSION
 */
function setMeta() {

    if (isset($_GET["meta"])) {
        $_SESSION["meta"] = substr($_GET["meta"], 0, 2);
    } else if (empty($_SESSION["meta"])) {
        $_SESSION["meta"] = '';
    }
}


/**
 * Cleans and stores the selected keywords
 * @todo Clean and format the query 
 */
function setKeywords() {

    if (isset($_GET["q"]) && $_SESSION["q"] != '' && $_GET["q"] != $_SESSION["q"]) {
        unset($_SESSION['total']);
    }
    
    if (isset($_GET["q"]) && $_GET["q"] != 'index') {
        $_SESSION["q"] = $_GET["q"];
    } else {
        $_SESSION['q'] = '';
    }
    
    if (empty($_SESSION["q"])) {
        $_SESSION["q"] = '';
    }
}


/**
 * Sets the labels var based on SESSION['q']
 */
function setLabels() {
    
    // Store the requested labels
    if (!empty($_SESSION['q'])) {
        $qs = explode('-', $_SESSION['q']);
        
        unset($_SESSION['labels']);
        
        // Encode query strings
        foreach ($qs as $q) {
        	$qencoded = encode_text($q);
        	$_SESSION['labels'][$qencoded] = $qencoded;
        }
    } else {
        unset($_SESSION['labels']);
    }
}


/**
 * Encodes a string to manage DB
 * @param string|array $var
 * @return string|array
 */
function encode_text($var) {
	
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			$var[$key] = encode_text($value);
		}
		
		return $var;
	} 
	
	return urlencode($var);	
}


/**
 * Decodes a DB string to display on screen
 * @param string|array $var
 * @return string|array
 */
function decode_text($var) {
	
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			$var[$key] = decode_text($value);
		}
		
		return $var;
	}
	
	return urldecode($var);
}


/**
 * Prints a simple debug notification
 *
 * @param mixed $text
 */
function e($var) {
    
    echo '<div class="debug">';
    if (is_object($var) || is_array($var)) {
        print_r($var);
    } else {
        echo $var;
    }
    echo '</div>'.chr(13).chr(10);
}
